import threading
import time

def thread_unsafe_demo():
    print("=== 线程不安全示例 ===")
    counter = 0
    thread_count = 5  # 线程数量
    iteration_count = 10000  # 每个线程的循环次数

    def increment():
        nonlocal counter
        for _ in range(iteration_count):
            # 读取当前值
            current = counter
            # 添加微小延迟，强制触发线程切换，放大竞态条件
            time.sleep(0.000001)  # 关键：增加线程切换概率
            # 修改并写回
            current += 1
            counter = current

    # 创建并启动线程
    threads = []
    for _ in range(thread_count):
        t = threading.Thread(target=increment)
        threads.append(t)
        t.start()

    # 等待所有线程完成
    for t in threads:
        t.join()

    # 输出结果
    expected = thread_count * iteration_count
    print(f"期望结果: {expected}")
    print(f"实际结果: {counter}")
    print(f"偏差值: {expected - counter}\n")

if __name__ == "__main__":
    # 多次运行，观察结果变化
    for i in range(3):
        print(f"第{i+1}次运行:")
        thread_unsafe_demo()
